#include "AudioRecordThread.h"

AudioRecordThread::AudioRecordThread()
{

}
void AudioRecordThread::Init()
{
	Stop();
	fmt.setSampleRate(sampleRate);
	fmt.setChannelCount(channelCount);
	fmt.setSampleSize(sampleSize);
	fmt.setSampleType(QAudioFormat::UnSignedInt);
	fmt.setByteOrder(QAudioFormat::LittleEndian);
	fmt.setCodec("audio/pcm");
	input = new QAudioInput(fmt);
	io = input->start();
}

void AudioRecordThread::Start()
{
	Init();
	fp = fopen(outFilePath.toStdString().c_str(), "wb");
	if (!fp) {
		qDebug() << "创建输出音频文件失败";
		return;
	}
	//开始录制音频
	this->start();
}

void AudioRecordThread::Stop()
{
	isRecord = false;
	if (io) {
		io->close();
		io = NULL;
	}
	if (input) {
		input->stop();
		input = NULL;
	}
	wait();//等待线程结束
}

void AudioRecordThread::run()
{
	int bufferLength = 1024;
	char* buf = new char[bufferLength];
	while (isRecord)
	{
		int br = input->bytesReady();
		if (br < bufferLength)continue;
		int len = io->read(buf, bufferLength);
		fwrite(buf, 1, len, fp);
		qDebug() << len << "*";
	}
	fclose(fp);

}
AudioRecordThread::~AudioRecordThread()
{
}
